﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace BeerManagementSystem
{
    /// <summary>
    /// Interaktionslogik für ReadCard.xaml
    /// </summary>
    public partial class ReadCard : UserControl
    {
        private ICardReader _cardReader;

        public String name { get; set; }

        private User cardOwner;

        public EventHandler cardRead;

        LogWriter log;

        public int CardIdentity { get; set; }
        LinqToBeerDataContext linq;

        public ReadCard(LogWriter log)
        {
            this.log = log;
            InitializeComponent();
            linq = new LinqToBeerDataContext();
            Window_Loaded(null,null);
        }        

        

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            if (name != null)
            {
                instructionLabel.Content = String.Format("Jetzt die Karte für {0} durchziehen", name);
                
            }
            else
            {
                instructionLabel.Content = "Jetzt die Karte durchziehen, die eingelesen werden soll...";
            }
            

            

#if DEBUG
            _cardReader = new EmulatedCardReader();
#else
            _cardReader = new MagTekCardReader();
#endif

            _cardReader.CardRead += new EventHandler<CardReadEventArgs>(_cardReader_CardRead);

            _cardReader.AcceptNextCard();
        }

        void _cardReader_CardRead(object sender, CardReadEventArgs e)
        {
            CardIdentity = e.CardIdentity;
            setCardOwner();
            instructionLabel.Content = String.Format("Spieler {0} wurde erfasst", cardOwner.FirstName);

            
        }
        void setCardOwner()
        {
            var cardResult =
                from c in linq.Card
                where c.ID == CardIdentity
                select c;
            if (cardResult.Count() == 1) cardOwner = cardResult.First().User;
            
            cardRead(this, null);
        }
        public User getCardOwner()
        {
            return cardOwner;
        }
    }
}
